package com.systop.scos.msg.webapp;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.systop.common.modules.fileattch.model.FileAttch;
import com.systop.common.modules.security.user.UserUtil;
import com.systop.common.modules.security.user.model.User;
import com.systop.common.modules.security.user.service.UserManager;
import com.systop.core.Constants;
import com.systop.core.dao.support.Page;
import com.systop.core.util.PageUtil;
import com.systop.core.webapp.struts2.action.JsonCrudAction;
import com.systop.scos.msg.MsgConstants;
import com.systop.scos.msg.model.Message;
import com.systop.scos.msg.service.MessageManager;

@SuppressWarnings({"serial", "rawtypes"})
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class MessageAction extends JsonCrudAction<Message, MessageManager> {

	/** 附件序列,ID以","分割 */
	private String fileattchids;

	/** 接收人 序列 */
	private String receiverIds;

	private Date startDate;

	private Date endDate;
	
	//发件箱标识
	private final String sendType = "s";
	
	//收件箱标识
	private final String receiveType = "r";
	
	private List<FileAttch> fileAttchs = null;
	
	private List newMsgs = null;
	
	//用户管理类
	@Autowired
	private UserManager userManager;

	/**
	 * 新建站内短信
	 * 
	 * @return
	 */
	public String newMsg() {
		getModel().setSender(UserUtil.getPrincipal(getRequest()));	
		getModel().setReceiver(userManager.getUser(receiverIds));//回复信息时得到收信人
		return INPUT;
	}

	/**
	 * 发送信息
	 * 
	 * @return
	 */
	public String sendMsg() {
		List<User> receivers = getReceivers();
		if (receivers != null) {
			for (User receiver : receivers) {
				Message msg = new Message();
				msg.setSender(UserUtil.getPrincipal(getRequest()));
				msg.setReceiver(receiver);
				//msg.setTitle(getModel().getTitle());
				if (StringUtils.isNotBlank(fileattchids)){
					msg.setFileIds(fileattchids);
				}
				msg.setCreateTime(new Date());
				msg.setContent(getModel().getContent());
				msg.setIsRead(Constants.NO);
				msg.setReceiverDel(MsgConstants.NOMAL);//未移除
				msg.setSenderDel(MsgConstants.NOMAL);
				getManager().save(msg);
			}
		}
		return SUCCESS;
	}

	/**
	 * 已发信息列表
	 * 
	 * @return
	 */
	public String sendIndex() {
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		Map<String, Object> query = getQueryAndPam(sendType);
		page = getManager().pageQuery(page, (String) query.get("hql"),
				(Object[]) query.get("args"));
		restorePageData(page);
		return "sendIndex";
	}

	public String receiveIndex() {
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		Map<String, Object> query = getQueryAndPam(receiveType);
		page = getManager().pageQuery(page, (String) query.get("hql"),
				(Object[]) query.get("args"));
		restorePageData(page);
		return "receiveIndex";
	}

	/**
	 * 获得查询条件和参数
	 * 
	 * @return
	 */
	private Map<String, Object> getQueryAndPam(String type) {
		User u = UserUtil.getPrincipal(getRequest());
		Assert.assertNotNull("当前登录用户为空!", u);
		Assert.assertNotNull("type 不能为空!", type);
		Map<String, Object> query = new HashMap<String, Object>();

		StringBuffer hql = new StringBuffer("from Message m");
		List<Object> args = new ArrayList<Object>();

		if (sendType.equals(type)) {
			hql.append(" where m.sender.id = ? and m.senderDel = 0");//未移除的
		} else if (receiveType.equals(type)) {
			hql.append(" where m.receiver.id = ? and m.receiverDel = 0");//未移除的
		}

		args.add(u.getId());
//		// 根据标题查询
//		if (getModel().getTitle() != null) {
//			hql.append(" and m.title like ?");
//			args.add("%" + getModel().getTitle() + "%");
//		}
		// 根据接收人查询
		if (getModel().getReceiver() != null
				&& getModel().getReceiver().getName() != null) {
			hql.append(" and m.receiver.name like ?");
			args.add("%" + getModel().getReceiver().getName() + "%");
		}
		// 根据发送人查询
		if (getModel().getSender() != null
				&& getModel().getSender().getName() != null) {
			hql.append(" and m.sender.name like ?");
			args.add("%" + getModel().getSender().getName() + "%");
		}
		if (startDate != null && endDate != null) {
			hql.append(" and (m.createTime between ? and ?)");
			args.add(startDate);
			args.add(endDate);
		}
		hql.append(" order by m.createTime desc");
		query.put("hql", hql.toString());
		query.put("args", args.toArray());
		return query;
	}

	@SuppressWarnings("unchecked")
	public String view() {
		if (getModel() != null && getModel().getId() != null) {
			String fileIds = getModel().getFileIds();
			if (fileIds != null && fileIds.endsWith(",")){
				fileIds = fileIds.substring(0, fileIds.lastIndexOf(","));
				String hql = "from FileAttch f where f.id in (" + fileIds + ")";
				fileAttchs = getManager().getDao().query(hql);
			}
			String updateState = getRequest().getParameter("updateState");
			if ("Y".equals(updateState)){
				getModel().setIsRead(Constants.YES);
				getManager().save(getModel());
			}
		}
		return VIEW;
	}
	
	/**
	 * 收件箱移除
	 */
	public String receiveDel() {
		setModel(getManager().get(getModel().getId()));
		getModel().setReceiverDel(MsgConstants.DELETE);//移除
		getManager().update(getModel());
		return "receives";	
	}
	
	/**
	 * 发件箱移除
	 */
	public String sendDel() {
		setModel(getManager().get(getModel().getId()));
		getModel().setSenderDel(MsgConstants.DELETE);//移除
		getManager().update(getModel());
		return SUCCESS;
	}
	
	/**
	 *  收件箱批量移除
	 */
	public String receiveRemove() {
		if (selectedItems != null){
			Message message = null;
			for(Serializable id : selectedItems){
				message = getManager().get(convertId(id));
				message.setReceiverDel(MsgConstants.DELETE);//设置receiverDel的值
				getManager().save(message);
			}
		}
		return "receives";
	}
	
	/**
	 * 发件箱批量移除
	 */
	public String sendRemove() {
		if (selectedItems != null){
			Message message = null;
			for(Serializable id : selectedItems){
				message = getManager().get(convertId(id));
				message.setSenderDel(MsgConstants.DELETE);//设置senderDel的值
				getManager().save(message);
			}
		}
		return SUCCESS;
	}
	
	/**
	 * 获取接收用户序列
	 * 
	 * @return
	 */
	private List<User> getReceivers() {
		List<User> receivers = null;
		if (StringUtils.isNotBlank(receiverIds)) {
			receivers = new ArrayList<User>();
			String[] uIds = receiverIds.split(",");
			for (String id : uIds) {
				if (StringUtils.isNumeric(id)) {
					User u = getManager().getDao().get(User.class,
							Integer.valueOf(id));
					if (u != null) {
						receivers.add(u);
					}
				}
			}
		}
		return receivers;
	}
	
	/**
	 * 异步查询未读信息
	 * @return
	 */
	public String checkNewMsgs(){
		User user = UserUtil.getPrincipal(getRequest());
		String hql = "select m.id as id, m.content as content from Message m where m.receiver.id = ? and m.isRead = ? and m.receiverDel = ? order by m.createTime desc";
		newMsgs = getManager().query(hql, new Object[]{user.getId(), Constants.NO, MsgConstants.NOMAL});
		return "newmsg";
	}

	public String getFileattchids() {
		return fileattchids;
	}

	public void setFileattchids(String fileattchids) {
		this.fileattchids = fileattchids;
	}

	public String getReceiverIds() {
		return receiverIds;
	}

	public void setReceiverIds(String receiverIds) {
		this.receiverIds = receiverIds;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
	
	public List<FileAttch> getFileAttchs() {
		return fileAttchs;
	}

	public List getNewMsgs() {
		return newMsgs;
	}

}
